package com.hu.web.servlet;

import com.hu.web.dao.UserDao;
import com.hu.web.dao.impl.UserDaoImpl;
import com.hu.web.entity.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

public class RegisterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        String username = request.getParameter("username");
//        String password = request.getParameter( "password");
//        String email = request.getParameter("email");
//        User addUser = new User(null, username, password, email);


        Map<String, String[]> parameterMap = request.getParameterMap();
        User addUser = new User();
        try {
            // 使用 BeanUtils 将 map 集合中的数据映射到 javaBean 内
            BeanUtils.populate(addUser, parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println("addUser: " + addUser);

        UserDao userDao = new UserDaoImpl();
        User user = userDao.findUserByUsername(addUser.getUsername());

        if (null == user) {
            userDao.addUser(addUser);
            request.getRequestDispatcher("success.html").forward(request, response);
        } else {
            request.getRequestDispatcher("error.html").forward(request, response);
        }
    }

}
